/**
 * Created by tdzl2003 on 8/25/16.
 */

import React, { PropTypes } from 'react';
import Subscribe from '../Subscribe';
import LoginModal from './LoginModal';
import ChangePwdModal from './ChangePwdModal';
import Rpc from '../../logics/rpc';
import Auth, { getUserInfo, logout } from '../../logics/auth';

export default class LoginState extends React.Component {
  state = {
    userInfo: getUserInfo(),
    showLoginModal: !getUserInfo(),   // Display login modal when not logged in.
  };
  showLoginModal = () => {
    this.setState({
      showLoginModal: true,
    });
  };
  dismissLoginModal = () => {
    this.setState({
      showLoginModal: false,
    });
  };
  showChangePwd = () => {
    this.setState({
      changePwdVisible: true,
    });
  };
  dismissChangePwd = () => {
    this.setState({
      changePwdVisible: false,
    });
  };
  updateUserInfo = userInfo => {
    if (userInfo) {
      this.setState({
        userInfo,
      });
    } else {
      this.setState({
        userInfo: null,
        showLoginModal: true,
      });
    }
  };
  renderContent() {
    const {
      userInfo,
      showLoginModal,
      changePwdVisible,
    } = this.state;
    if (userInfo === null) {
      return (
        <ul>
          <LoginModal
            visible={showLoginModal}
            dismiss={this.dismissLoginModal}
          />
          <li><a onClick={this.showLoginModal}>登录</a></li>
        </ul>
      );
    }
    return (
      <ul>
        <LoginModal
          visible={showLoginModal}
          dismiss={this.dismissLoginModal}
        />
        <ChangePwdModal
          visible={changePwdVisible}
          dismiss={this.dismissChangePwd}
        />
        <li>{userInfo.account}</li>
        <li>|</li>
        <li><a onClick={this.showChangePwd}>修改密码</a></li>
        <li>|</li>
        <li><a onClick={logout}>登出</a></li>
      </ul>
    );
  }
  render() {
    return (
      <Subscribe target={Auth} eventName="userInfoChanged" listener={this.updateUserInfo}>
        <Subscribe target={Rpc} eventName="invalidToken" listener={logout}>
          {this.renderContent()}
        </Subscribe>
      </Subscribe>
    );
  }
}